package com.songhq.data.redis;

import java.util.ArrayList;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

/**
 * JedisConnectionFactory 和 LettuceConnectionFactory
 * 都是RedisConnectionFactory的实现类
 * 
 * @author songhq
 *
 */
@Configuration
@PropertySource("classpath:config/redis.properties")
public class RedisConfig {
	// RedisConnectionFactory

	@Value("${redis.maxIdle}")
	private Integer maxIdle;

	@Value("${redis.maxTotal}")
	private Integer maxTotal;

	@Value("${redis.maxWaitMillis}")
	private Integer maxWaitMillis;

	@Value("${redis.minEvictableIdleTimeMillis}")
	private Integer minEvictableIdleTimeMillis;

	@Value("${redis.numTestsPerEvictionRun}")
	private Integer numTestsPerEvictionRun;

	@Value("${redis.timeBetweenEvictionRunsMillis}")
	private long timeBetweenEvictionRunsMillis;

	@Value("${redis.testOnBorrow}")
	private boolean testOnBorrow;

	@Value("${redis.testWhileIdle}")
	private boolean testWhileIdle;

	/**
	 * JedisPoolConfig 连接池
	 * 
	 * @return
	 */
	@Bean
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		// 最大空闲数
		jedisPoolConfig.setMaxIdle(maxIdle);
		// 连接池的最大数据库连接数
		jedisPoolConfig.setMaxTotal(maxTotal);
		// 最大建立连接等待时间
		jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
		// 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
		jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		// 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
		jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
		// 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
		jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		// 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
		jedisPoolConfig.setTestOnBorrow(testOnBorrow);
		// 在空闲时检查有效性, 默认false
		jedisPoolConfig.setTestWhileIdle(testWhileIdle);
		return jedisPoolConfig;
	}

	/**
	 * 单机版配置 spring JedisConnectionFactory 没有提供
	 * JedisConnectionFactory（RedisStandaloneConfiguration ，jedisPoolConfig）
	 * 它认为单机版不用配置连接池等信息，也就是认为生产时不可能使用单机版，开发的时候就不用配了
	 */
	@Bean
	public RedisConnectionFactory JedisConnectionFactory() {
	
		//reids单例模式,这个没有set方法注入到JedisConnectionFactory所以只能根据构造方法
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		//地址  端口  密码  数据库选择  spring认为这才是最基本的
		redisStandaloneConfiguration.setHostName("47.100.212.206");
		redisStandaloneConfiguration.setPort(6379);
		
		RedisPassword of = RedisPassword.of("song0426");
		redisStandaloneConfiguration.setPassword(of);//若有密码提供密码
		redisStandaloneConfiguration.setDatabase(1);
		JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
	
		return jedisConnectionFactory;
	}
	
	/**
	 * redis sentinel版配置
	 * @param jedisPoolConfig
	 * @return
	 */
//	@Bean
//	public RedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig ) {
//	
//		//使用RedisSentinelConfiguration进行配置
//		RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
//		redisSentinelConfiguration.setDatabase(0);
//		redisSentinelConfiguration.setMaster("mymaster");
//		ArrayList<RedisNode> arrayList = new ArrayList<>();
//		RedisNode redisNode1 = new RedisNode("127.0.0.1", 5000);
//		RedisNode redisNode2 = new RedisNode("127.0.0.1", 5001);
//		RedisNode redisNode3 = new RedisNode("127.0.0.1", 5002);
//		arrayList.add(redisNode1);
//		arrayList.add(redisNode2);
//		arrayList.add(redisNode3);
//		redisSentinelConfiguration.setSentinels(arrayList);
//		JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration,jedisPoolConfig);
//	
//		return jedisConnectionFactory;
//	}
	
	/**
	 * redis集群版配置
	 * @param jedisPoolConfig  配置有问题，没有通过
	 * @return
	 */
//	@Bean
//	public RedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig ) {
//		
//		
//		HashSet<String> hashSet = new HashSet<String>();
//		hashSet.add("47.100.212.206:7000");
//		hashSet.add("47.100.212.206:7001");
//		hashSet.add("47.100.212.206:7002");
//		hashSet.add("47.100.212.206:7003");
//		hashSet.add("47.100.212.206:7004");
//		hashSet.add("47.100.212.206:7005");
//		RedisClusterConfiguration clusterConf = new RedisClusterConfiguration(hashSet);
//		clusterConf.setMaxRedirects(3);
//		JedisConnectionFactory factory = new JedisConnectionFactory(clusterConf,jedisPoolConfig);
//        return factory;
//	}
	/**
	 * 实例化 RedisTemplate 对象
	 *
	 * @return
	 */

	@Bean
	public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
		return redisTemplate;
	}

	/**
	 * 设置数据存入 redis 的序列化方式,并开启事务
	 * 
	 * @param redisTemplate
	 * @param factory
	 */
	private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
		// 如果不配置Serializer，那么存储的时候缺省使用String，如果用User类型存储，那么会提示错误User can't cast to
		// String！
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		 // 开启事务
		redisTemplate.setEnableTransactionSupport(true);
		redisTemplate.setConnectionFactory(factory);
	}

	/**
	 * 注入封装RedisTemplate @Title: redisUtil @return RedisUtil @autor lpl @date
	 * 2017年12月21日 @throws
	 */
	@Bean(name = "redisUtil")
	public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
		RedisUtil redisUtil = new RedisUtil();
		redisUtil.setRedisTemplate(redisTemplate);
		return redisUtil;
	}

}
